<template>
  <div class="layer p-3 gap-3">

    <div class="section">
      <div class="form-item-inline">
        <div class="title-flag bg-red-5"></div>
        <div class="title">基本参数</div>
      </div>
      <xoVerticalExpand :expand="true" :gap="3">
        <xoFormInput label="套餐名称" placeholder="(必填项)" v-model="packageBaseModel.name.value"
          :ruleMessage="packageBaseModel.name.ruleMessage" @onValid="packageBaseModel.name.valid" />
        <div class="inline-flex justify-between gap-3">
          <xoFormInput type="digit" label="实价(￥)" placeholder="(必填项)"
            v-model.number="packageBaseModel.actualPrice.value" :ruleMessage="packageBaseModel.actualPrice.ruleMessage"
            @onValid="packageBaseModel.actualPrice.valid" />
          <xoFormInput type="digit" label="原价(￥)" placeholder="(必填项)" v-model.number="packageBaseModel.price.value"
            :ruleMessage="packageBaseModel.price.ruleMessage" @onValid="packageBaseModel.price.valid" />
        </div>
        <xoFormInput type="number" label="赠送积分" tips="不填写或者为0表示不赠送积分" v-model.number="packageBaseModel.points.value"
          :ruleMessage="packageBaseModel.points.ruleMessage" @onValid="packageBaseModel.points.valid" />
      </xoVerticalExpand>
    </div>

    <div v-if="isShowStore" class="section ">
      <div class="form-item-inline justify-between">
        <div class="form-item-inline">
          <div class="title-flag" :class="packageStoreModel.isUse ? 'bg-red-5' : 'bg-gray-400'"></div>
          <div class="title" :class="packageStoreModel.isUse ? '' : 'desc'">储值参数</div>
        </div>
        <switch v-if="showSwitch" :checked="packageStoreModel.isUse" type="switch"
          @change="packageStoreModel.isUse = !packageStoreModel.isUse">
        </switch>
      </div>
      <xoVerticalExpand :expand="packageStoreModel.isUse" :gap="3">
        <xoFormInput type="digit" label="基础金额(￥)" placeholder="(必填项)"
          v-model.number="packageStoreModel.baseAmount.value" :ruleMessage="packageStoreModel.baseAmount.ruleMessage"
          @onValid="handleChangeBaseAmount" />
        <xoFormInput type="digit" label="赠送金额(￥)" placeholder="(选填)" v-model.number="packageStoreModel.giveAmount.value"
          :ruleMessage="packageStoreModel.giveAmount.ruleMessage" @onValid="handleChangeGiveAmount"
          tips="为0则表示不赠送金额(选填)" />
        <xoFormInput type="digit" label="实际余额(￥)" placeholder="(必填项)" tips="实际余额 = 基础金额 + 赠送金额"
          v-model.number="packageStoreModel.balanceAmount.value"
          :ruleMessage="packageStoreModel.balanceAmount.ruleMessage" @onValid="packageStoreModel.balanceAmount.valid" />
        <xoFormNumberInput type="number" label="折扣(%)" :min="0" :max="100" tips="0或者100表示不打折(选填)"
          v-model.number="packageStoreModel.discount.value" :ruleMessage="packageStoreModel.discount.ruleMessage"
          @onValid="packageStoreModel.discount.valid">
          <template #footer>
            <div class="mt-1 desc-xs">折扣快选</div>
            <div class="mt-1 form-item-inline flex-wrap gap-2">
              <div v-for="(discount) in discountData" :key="discount.name" class="tab-button"
                @click.stop="packageStoreModel.discount.value = discount.value">{{ discount.name }}</div>
            </div>
          </template>
        </xoFormNumberInput>
        <xoFormNumberInput label="有效期(天)" :min="0" :max="999999" tips="0表示永久有效(选填)"
          v-model="packageStoreModel.term.value" :ruleMessage="packageStoreModel.term.ruleMessage"
          @onValid="packageStoreModel.term.valid">
          <template #footer>
            <div class="mt-1 desc-xs">有效期快选</div>
            <div class="mt-1 grid grid-cols-5 gap-2">
              <div v-for="(term) in termData" :key="term.name" class="tab-button"
                @click.stop="packageStoreModel.term.value = term.value">{{ term.name }}</div>
            </div>
          </template>
        </xoFormNumberInput>

      </xoVerticalExpand>
    </div>

    <div v-if="isShowCounter" class="section">
      <div class="form-item-inline justify-between">
        <div class="form-item-inline">
          <div class="title-flag" :class="packageCounterModel.isUse ? 'bg-red-5' : 'bg-gray-400'"></div>
          <div class="title" :class="packageCounterModel.isUse ? '' : 'desc'">计次参数</div>
        </div>
        <switch v-if="showSwitch" :checked="packageCounterModel.isUse" type="switch"
          @change="packageCounterModel.isUse = !packageCounterModel.isUse">
        </switch>
      </div>
      <xoVerticalExpand :expand="packageCounterModel.isUse" :gap="3">

        <xoFormNumberInput label="有效期统一设置" tips="" v-model="term">
          <template #footer>
            <div class="mt-1 desc-xs">有效期快选</div>
            <div class="mt-1 grid grid-cols-5 gap-2">
              <div v-for="(t) in termData" :key="t.name" class="tab-button" @click.stop="term = t.value">{{ t.name }}
              </div>
            </div>
          </template>
        </xoFormNumberInput>

        <div @click="selectProduct">
          <xoFormNavigate label="计次商品" placeholder="(必选项)点击选择" :content="getProductTotal"
            :ruleMessage="packageCounterModel.products.ruleMessage" @valid="packageCounterModel.products.valid">
          </xoFormNavigate>
        </div>

        <div v-if="packageCounterModel.products.value.length" class="mt-3 form-item gap-3">
          <div v-for="(p, index) in packageCounterModel.products.value" :key="p.name" class="flex flex-col gap-1">
            <div class="form-item-inline">
              <div class="grow form-item-inline">
                <div class="w-2 h-2 bg-emerald-5"></div>
                <div class="font-bold">{{ p.name }}({{ p.balanceCount }}次)</div>
              </div>
              <div class="flex-shrink-0 inline-flex items-center gap-2 " @click="handleClickRemoveProductItem(p)">
                <div class="icon-sm i-mdi-drag-vertical"></div>
                <div class="text-xs text-red-5">移除</div>
                <div class="icon-sm i-mdi-close text-red-5"></div>
              </div>
            </div>
            <div class="grid grid-cols-3 gap-3">
              <xoFormNumberInput type="number" label="基本次数" :min="1" v-model.number="p.baseCount" />
              <xoFormNumberInput type="number" label="赠送次数" v-model.number="p.giveCount" />
              <xoFormNumberInput type="number" label="有效天数" :min="0" :max="99999" v-model.number="p.term" />
            </div>
            <div v-if="index !== packageCounterModel.products.value.length - 1" class="mt-2 divider-x"></div>
          </div>
        </div>
      </xoVerticalExpand>
    </div>

    <div v-if="isShowTime" class="section ">
      <div class="form-item-inline justify-between">
        <div class="form-item-inline">
          <div class="title-flag" :class="packageTimeModel.isUse ? 'bg-red-5' : 'bg-gray-400'"></div>
          <div class="title" :class="packageTimeModel.isUse ? '' : 'desc'">计时参数</div>
        </div>
        <switch v-if="showSwitch" :checked="packageTimeModel.isUse" type="switch"
          @change="packageTimeModel.isUse = !packageTimeModel.isUse">
        </switch>
      </div>
      <xoVerticalExpand :expand="packageTimeModel.isUse" :gap="3">
        <xoFormNumberInput label="有效天数(天)" :min="0" :max="99999" v-model="packageTimeModel.term.value">
          <template #footer>
            <div class="mt-1 desc-xs">有效期快选</div>
            <div class="mt-1 grid grid-cols-4 gap-2">
              <div v-for="(term) in termData.slice(0, 4)" :key="term.name" class="tab-button"
                @click.stop="packageTimeModel.term.value = term.value">{{ term.name }}</div>
            </div>
          </template>
        </xoFormNumberInput>
      </xoVerticalExpand>
    </div>

    <div class="section">

      <div class="form-item-inline justify-between">
        <div class="form-item-inline">
          <div class="title-flag "></div>
          <div class="title">优惠券</div>
        </div>
        <div class="flex-shrink-0 text-emerald-5" @click="selectCoupon">选择优惠券</div>
      </div>

      <div v-if="packageCouponModel.coupon.value.length" class="form-item-inline flex-wrap gap-2">
        <div v-for="(coupon) in couponData" :key="coupon"
          class="inline-flex items-center p-2 justify-between b-1 b-dashed b-orange-4 bg-orange-1 rounded-lg">
          <div class="title-sm">{{ coupon }}</div>
          <div class="icon i-mdi-close text-orange-4"></div>
        </div>
      </div>

    </div>

    <div class="w-full bg-inherit">

      <div class="desc">套餐预览</div>

      <div class="section bg-gradient-to-br to-white to-20% b-2 b-solid shadow rounded-lg gap-2"
        :class="` ${getBColor} ${getBGFromColor} `">
        <div class="form-item-inline justify-between">
          <div class="title-lg">{{ packageBaseModel.name.value }}</div>
          <div v-if="packageBaseModel.points.value" class="text-rose-5">赠送积分{{ packageBaseModel.points.value }}</div>
        </div>
        <div class="flex flex-row items-center justify-center gap-2">
          <div
            v-if="packageBaseModel.price.value !== packageBaseModel.actualPrice.value && packageBaseModel.price.value !== 0"
            class="inline-flex items-center desc line-through">原价:￥{{ packageBaseModel.price.value }}</div>
          <div class="title-4xl text-rose-5">{{ packageBaseModel.actualPrice.value ?
            `${packageBaseModel.actualPrice.value}`
            : '免费'
          }}
          </div>
        </div>
        <div class="form-item-inline justify-center b-1 b-solid rounded-lg text-white" :class="getBGColor">
          <div v-if="packageStoreModel.isUse" class="text-white">储值{{ packageStoreModel.balanceAmount.value }}元</div>
          <div v-if="packageStoreModel.isUse" class="desc-xs text-white">/</div>
          <div v-if="packageCounterModel.isUse" class="text-white">{{ getProductTotal }}</div>
          <div v-if="packageCounterModel.isUse && packageTimeModel.isUse" class="text-xs text-white">/</div>
          <div v-if="packageTimeModel.isUse" class="text-white">计时{{ packageTimeModel.term.value }}天</div>
          <div v-if="packageCouponModel.coupon.value.length" class="desc-xs text-white">/</div>
          <div v-if="packageCouponModel.coupon.value.length" class="text-white">
            优惠券{{ packageCouponModel.coupon.value.length }}张
          </div>
        </div>
        <div class="form-item-inline justify-center" @click.stop="showPackageDetail = !showPackageDetail">
          <div class="desc">{{ showPackageDetail ? '收起详情' : '展开详情' }}</div>
          <div class="iccon-sm" :class="showPackageDetail ? 'arrow-up' : 'arrow-down'"></div>
        </div>

        <xoVerticalExpand :expand="showPackageDetail">
          <div class="form-item gap-2">

            <div v-if="packageStoreModel.isUse" class="form-item p-2 gap-2">
              <div class="form-item-inline justify-between">
                <div class="desc">储值</div>
                <div class="desc">{{ packageStoreModel.balanceAmount.value }}元</div>
              </div>
              <div class="divider-x"></div>
              <div class="form-item gap-1">
                <div class="form-item-inline justify-between">
                  <div class="title-sm">基础金额</div>
                  <div class="title-sm">{{ packageStoreModel.baseAmount.value }}元</div>
                </div>
                <div class="form-item-inline justify-between">
                  <div class="title-sm">赠送金额</div>
                  <div class="title-sm">{{ packageStoreModel.giveAmount.value }}元</div>
                </div>
                <div v-if="packageStoreModel.discount.value !== 0 && packageStoreModel.discount.value !== 100"
                  class="form-item-inline justify-between">
                  <div class="title-sm">折扣(%)</div>
                  <div class="title-sm">{{ packageStoreModel.discount.value }}折</div>
                </div>
                <div class="form-item-inline justify-between">
                  <div class="title-sm">有效期</div>
                  <div class="title-sm">{{ packageStoreModel.term.value || '永久有效' }}天</div>
                </div>
              </div>
            </div>

            <div v-if="packageCounterModel.isUse" class="form-item p-2 gap-2">
              <div class="grid grid-cols-10 gap-1">
                <div class="col-span-4 desc">计次商品</div>
                <div class="col-span-2 desc text-right">基本(次)</div>
                <div class="col-span-2 desc text-right">赠送(次)</div>
                <div class="col-span-2 desc text-right">有效(天)</div>
              </div>
              <div class="divider-x"></div>
              <div v-if="packageCounterModel.products.value.length" class="form-item gap-1">
                <div v-for="p in packageCounterModel.products.value" :key="p.name" class="grid grid-cols-10 gap-1">
                  <div class="col-span-4 title-sm">{{ p.name }}</div>
                  <div class="col-span-2 title-sm text-right">{{ p.baseCount }}</div>
                  <div class="col-span-2 title-sm text-right">{{ p.giveCount }}</div>
                  <div class="col-span-2 title-sm text-right">{{ p.term || '永久有效' }}天</div>
                </div>
                <div class="divider-x"></div>
                <div class="grid grid-cols-10 gap-1">
                  <div class="col-span-4 title-sm">总计{{ packageCounterModel.products.value.length }}项</div>
                  <div class="col-span-2 title-sm text-right">{{ 6 }}</div>
                  <div class="col-span-2 title-sm text-right">{{ 1 }}</div>
                  <div class="col-span-2 title-sm text-right"></div>
                </div>
              </div>
            </div>

            <div v-if="packageTimeModel.isUse" class="form-item-inline p-2">
              <div class="desc-xs">计时</div>
              <div class="title-sm">{{ packageTimeModel.term.value }}</div>
              <div class="desc-xs">天</div>
            </div>

            <div v-if="packageCouponModel.coupon.value.length" class="form-item p-2 gap-2">
              <div class="desc">优惠券({{ packageCouponModel.coupon.value.length }}张)</div>
              <div class="divider-x"></div>
              <div class="form-item-inline flex-wrap gap-2">
                <div v-for="c in packageCouponModel.coupon.value" :key="c"
                  class="inline-flex items-center p-2 justify-between b-1 b-dashed b-orange-4 bg-orange-1 rounded-lg">
                  <div class="title-sm">{{ c }}</div>
                </div>
              </div>
            </div>

            <div class="mt-2 form-item-inline justify-center" @click.stop="showPackageDetail = false">
              <div class="desc">收起详情</div>
              <div class="iccon-sm arrow-up"></div>
            </div>
          </div>
        </xoVerticalExpand>
      </div>
    </div>

    <div class="section">
      <div class="grid grid-cols-4 gap-3">
        <div class="col-span-0 btn-default" @click="handleClickReset">重置</div>
        <div class="col-span-3 btn-primary" @click="handleClickSave">保存</div>
      </div>
    </div>

  </div>
</template>

<script setup lang='ts'>

import xoFormInput from '@/components/xoUI/xoFormInput.vue';
import xoFormNumberInput from '@/components/xoUI/xoFormNumberInput.vue';
import xoFormNavigate from '@/components/xoUI/xoFormNavigate.vue';
import xoVerticalExpand from '@/components/xoUI/xoVerticalExpand.vue';
import { onLoad } from '@dcloudio/uni-app';
import { computed, ref } from 'vue';
import usePackage from '@/hooks/usePackage'
import { IProduct } from '@/validator/package.valid';

const {
  packageBaseModel,
  packageStoreModel,
  packageCounterModel,
  packageTimeModel,
  packageCouponModel,


  packageValid,
  packageReset,
} = usePackage()

const mode = ref(0)
const showPackageDetail = ref(false)
const term = ref(0)

const discountData = [
  { name: '85折', value: 85 },
  { name: '88折', value: 88 },
  { name: '90折', value: 90 },
  { name: '95折', value: 95 },
  { name: '98折', value: 98 },
  { name: '无', value: 0 },
]

const termData = [
  { name: '一周', value: 7 },
  { name: '一月', value: 30 },
  { name: '半年', value: 180 },
  { name: '一年', value: 365 },
  { name: '永久', value: 0 },
]

const ProductData = ref<IProduct[]>([
  {
    name: '洗车',
    price: 60,
    actualPrice: 54,
    baseCount: 1,
    giveCount: 1,
    balanceCount: 2,
    term: 365,
  },
  {
    name: '光触媒治污',
    price: 380,
    actualPrice: 360,
    baseCount: 3,
    giveCount: 0,
    balanceCount: 3,
    term: 365,
  },
  {
    name: '精品封釉',
    price: 480,
    actualPrice: 450,
    baseCount: 2,
    giveCount: 0,
    balanceCount: 2,
    term: 365,
  },
])

const couponData = ['满50减5', '洗车券', '1000积分', '满00减10', '全场95折']

const selectProduct = () => {
  packageCounterModel.value.products.value = ProductData.value.map(p => p)
  packageCounterModel.value.products.valid(packageCounterModel.value.products.value)
}

const selectCoupon = () => {
  packageCouponModel.value.coupon.value = couponData.map(c => c)
}

onLoad((q) => {

  if (q && q.mode) {
    mode.value = Number(q.mode)
    if (mode.value === 3) {
      packageStoreModel.value.isUse = true
      packageCounterModel.value.isUse = true
      packageTimeModel.value.isUse = true
    }
    else {
      packageStoreModel.value.isUse = mode.value === 0
      packageCounterModel.value.isUse = mode.value === 1
      packageTimeModel.value.isUse = mode.value === 2
    }
  }
})

const handleChangeBaseAmount = () => {
  if (typeof packageStoreModel.value.baseAmount.value === 'number' && typeof packageStoreModel.value.giveAmount.value === 'number')
    packageStoreModel.value.balanceAmount.value = packageStoreModel.value.baseAmount.value + packageStoreModel.value.giveAmount.value
  packageStoreModel.value.baseAmount.valid(packageStoreModel.value.baseAmount.value)
}

const handleChangeGiveAmount = () => {
  if (typeof packageStoreModel.value.baseAmount.value === 'number' && typeof packageStoreModel.value.giveAmount.value === 'number')
    packageStoreModel.value.balanceAmount.value = packageStoreModel.value.baseAmount.value + packageStoreModel.value.giveAmount.value
  packageStoreModel.value.giveAmount.valid(packageStoreModel.value.giveAmount.value)
}

const handleClickRemoveProductItem = (p: IProduct) => {
  packageCounterModel.value.products.value = packageCounterModel.value.products.value.filter(item => item.name !== p.name)
}

const handleClickReset = () => {
  uni.showModal({
    title: '重置将会导致已填写的数据丢失，确认重置吗？',
    confirmText: '重置',
    confirmColor: '#10b981',
    success: (success) => {
      if (success.confirm)
        packageReset()
    },
  })
}

const handleClickSave = () => {
  // 校验表单数据
  if (packageValid() === false) {
    uni.showToast({ title: '请完善信息', icon: 'none' })
    return
  }

  //... 保存数据
}

const getBGFromColor = computed(() => {
  const color = ['from-orange-1', 'from-sky-1', 'from-purple-1', 'from-emerald-1']
  return color[mode.value]
})

const getBColor = computed(() => {
  const color = ['b-orange-5', 'b-sky-5', 'b-purple-5', 'b-emerald-5']
  return color[mode.value]
})

const getBGColor = computed(() => {
  const color = ['bg-orange-5', 'bg-sky-5', 'bg-purple-5', 'bg-emerald-5']
  return color[mode.value]
})

const isShowStore = computed(() => {
  return mode.value === 0 || mode.value === 3
})

const isShowCounter = computed(() => {
  return mode.value === 1 || mode.value === 3
})

const isShowTime = computed(() => {
  return mode.value === 2 || mode.value === 3
})

const showSwitch = computed(() => {
  return mode.value === 3
})

const getProductTotal = computed(() => {
  let items = 0
  let counts = 0
  packageCounterModel.value.products.value.forEach(p => {
    items = items + 1
    counts = counts + p.baseCount + p.giveCount
  })
  if (items === 0)
    return ''
  else
    return `${items}项共${counts}次`
})


</script>

<style></style>